﻿var typeaheadUser = undefined;
var users = new Bloodhound({
    datumTokenizer: Bloodhound.tokenizers.obj.whitespace('Name'),
    queryTokenizer: Bloodhound.tokenizers.whitespace,
    remote: {
        url: urlUsers,
        wildcard: '%QUERY'
    }
});

function addRemoveUser() {
    var icon = $(this).find('span');
    if ($(this).prop('title') == 'Eliminar usuario') {
        icon.removeClass("glyphicon-remove");
        icon.addClass("glyphicon-ok");
        $(this).prop('title', 'Agregar usuario');
        $(this).closest('tr').find('.remove-user').val('true');
    }
    else {
        icon.removeClass("glyphicon-ok");
        icon.addClass("glyphicon-remove");
        $(this).prop('title', 'Eliminar usuario');
        $(this).closest('tr').find('.remove-user').val('false');
    }
}

function addRemovePermission() {
    $(this).val($(this).is(":checked"));
    if ($(this).hasClass('user-permission-adm')) {
        if ($(this).is(":checked")) {
            $(this).closest('tr').find('.user-permission').val(true);
            $(this).closest('tr').find('.user-permission').prop('checked', true);
        }
    }
    else {
        if (!$(this).is(":checked")) {
            $(this).closest('tr').find('.user-permission-adm').val(false);
            $(this).closest('tr').find('.user-permission-adm').prop('checked', false);
        }
    }
}

var grid = $("#grid-list").bootgrid({
    ajax: true,
    post: function () {
        /* To accumulate custom parameter with the request object */
        return {
            listId: ListId
        };
    },
    url: urlGetListData,
    formatters: {
        "selection": function(column, row)
        {
            if (hasDMLPermissions)
                return "<button type=\"button\" class=\"btn btn-xs btn-default selection-upload-file\" data-row-id=\"" + row.Id + "\"><span class=\"fontelloicon icon-upload-cloud-4\"></span></button>" +
                "<button type=\"button\" class=\"btn btn-xs btn-default selection-edit\" data-row-id=\"" + row.Id + "\"><span class=\"fontelloicon icon-edit\"></span></button> ";
        }
    },
    labels: {
        noResults: "Ningún elemento encontrado",
        infos: "{{ctx.start}} al {{ctx.end}} de {{ctx.total}} elementos",
        loading: "Cargando",
        refresh: "Actualizar",
        search: "Buscar"
    },
    navigation: 1,
    rowCount: -1,
    templates: {
        header: actions
    }
}).on("loaded.rs.jquery.bootgrid", function () {
    if (hasDMLPermissions === 'True') {
        grid.find(".selection-edit").on("click", function (e) {
            icon = $(this).find('.fontelloicon');
            icon.removeClass('icon-edit');
            icon.addClass('icon-spin3 animate-spin');
            EditItem($(this).data("row-id"), icon);
        });
        grid.find(".selection-upload-file").on("click", function (e) {
            icon = $(this).find('.fontelloicon');
            icon.removeClass('icon-upload-cloud-4');
            icon.addClass('icon-spin3 animate-spin');
            UploadFile($(this).data("row-id"), icon);
        });
    }
});

function restoreDeleteButton() {
    $('#deleteList').html('Eliminar');
}

$('#deleteList').bind('click', function () {
    if ($(this).text() === 'Eliminar') {
        $(this).html('¿Confirmar?');
        setTimeout(restoreDeleteButton, 1000);
        return false;
    }
    else {
        $('#Delete').val('true');
        return true;
    }
});

$('.typeahead').typeahead(null, {
    name: 'users',
    limit: 3,
    display: 'Name',
    source: users,
    templates: {
        empty: [
          '<div class="empty-message">',
            'Ningún usuario encontrado',
          '</div>'
        ].join('\n'),
        suggestion: Handlebars.compile('<div><b>{{UPN}}</b> - {{Name}}</div>')
    }
}).bind('typeahead:selected', function(obj, datum) {
        typeaheadUser = datum;
});

$('#btn-addUser').bind('click', function () {
    if (typeaheadUser != undefined) {
        usersCount = $('#tableUsers').find('tr.user-items').length;
        var row = '<tr class=\"user-items\">' +
            '<input class="remove-user" name="Users[' + usersCount + '].Delete" value="false" type="hidden">' +
            '<input name="Users[' + usersCount + '].UserUPN" value="' + typeaheadUser.UPN + '" type="hidden">' +
            '<input name="Users[' + usersCount + '].UserName" value="' + typeaheadUser.Name + '" type="hidden">' +
            '<td><span name="Users[' + usersCount +  '].UserName">' + typeaheadUser.Name + '</span></td>' +
            '<td><input class="user-permission" type="checkbox" name="Users[' + usersCount + '].DMLPermissions" value="False"> Modificar</td>' +
            '<td><input class="user-permission-adm" type="checkbox" name="Users[' + usersCount + '].DDLPermissions" value="False"> Modificar</td>' +
            '<td class="text-center"><button type="button" class="btn btn-default" title="Eliminar usuario"><span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button></td>' +
            '</tr>';
        row = $(row);
        usersCount++;
        row.find('.user-permission').bind('click', addRemovePermission);
        row.find('.user-permission-adm').bind('click', addRemovePermission);
        row.find('.btn-default').bind('click', addRemoveUser);
        $('#tableUsers tr:last').after(row);
        $('.typeahead').typeahead('val', '');
        typeaheadUser = undefined;
    }
});

$('#modalCreateColumn').on('show.bs.modal', function () {
    $('.modal-content').css('max-height', $(window).height() * 0.9);
});

$('#modalEditColumn').on('show.bs.modal', function () {
    $('.modal-content').css('max-height', $(window).height() * 0.9);
});

$('#modalAddItem').on('show.bs.modal', function () {
    $('.modal-content').css('max-height', $(window).height() * 0.9);
});

$('#modalAddItem').on('hidden.bs.modal', function (e) {
    $('#modalAddItem .modal-dialog').empty();
});

$('#modalEditItem').on('show.bs.modal', function () {
    $('.modal-content').css('max-height', $(window).height() * 0.9);
});

$('#modalEditItem').on('hidden.bs.modal', function (e) {
    $('#modalEditItem .modal-dialog').empty();
});

$('#modalUploadFile').on('show.bs.modal', function () {
    $('.modal-content').css('max-height', $(window).height() * 0.9);
});

$('#modalUploadFile').on('hidden.bs.modal', function (e) {
    $('#modalUploadFile .modal-dialog').empty();
});

function CreateColumn() {
    $('#modalCreateColumn .modal-dialog').load(urlAddColumn, function () {
        $("#modalCreateColumn").modal();
    });
}

function EditColumn() {
    if ((itemCount > 1) && $("#modalEditColumn").length) {
        $("#modalEditColumn").modal();
    }
}

function AddItem() {
    if (itemCount > 1) {
        $('#modalAddItem .modal-dialog').load(urlAddItem, function () {
            $("#modalAddItem").modal();
        });
    }
}

function EditItem(itemId, icon) {
        $('#modalEditItem .modal-dialog').load(urlEditItem + '&columnId=' + itemId, function () {
            $("#modalEditItem").modal();
            icon.removeClass('icon-spin3 animate-spin');
            icon.addClass('icon-edit');
        });
}

function UploadFile(itemId, icon) {
        $('#modalUploadFile .modal-dialog').load(urlUploadFile + '&columnId=' + itemId, function () {
            $("#modalUploadFile").modal();
            icon.removeClass('icon-spin3 animate-spin');
            icon.addClass('icon-upload-cloud-4');
        });
}

$('#tableUsers').find('.user-permission').bind('click', addRemovePermission);
$('#tableUsers').find('.user-permission-adm').bind('click', addRemovePermission);
$('#tableUsers').find('.btn-default').bind('click', addRemoveUser);


$('.selectpicker').selectpicker({});